﻿Imports SFDL.Core
Imports SFDL.Logging
Imports SFDL.LoaderExtensions
Imports SFDL.Loader.My.Resources

Public Class frm_settings

    Private Shared _log As NLog.Logger = NLog.LogManager.GetLogger("SettingsForm")
    Protected Friend Event SettingsUpdated(ByVal sender As Object, ByVal e As SettingsUpatedEventArgs)

#Region "Einstellungen Laden/Speichern"

    Private Sub cmd_save_settings_Click(sender As Object, e As EventArgs) Handles cmd_save_settings.Click

        Dim _tools As New Tools
        Dim _settings As New Settings
        Dim _unrar_settings As New UnRARSettings
        Dim _speedreport_settings As New SpeedreportSettings
        Dim _eventargs As New SettingsUpatedEventArgs

        Try

            _settings.DownloadDirectory = txt_download_dir.Text

            If ComB_Existing_File_Handling.SelectedIndex = 0 Then
                _settings.ExistingFileHandling = ExistingFileHandling.ResumeFile
            End If

            If ComB_Existing_File_Handling.SelectedIndex = 1 Then
                _settings.ExistingFileHandling = ExistingFileHandling.OverwriteFile
            End If

            _settings.Send2Tray = chk_send2tray.Checked

            _settings.PreventStandby = chk_prevent_standby.Checked

            _settings.CreateDownloadDir = chk_create_sub_folder.Checked
            _settings.CreateDownloadDirUseDescription = rd_sub_folder_description.Checked
            _settings.CreateDownloadDirUseFilename = rd_sub_folder_filename.Checked
            _settings.CreatePackageSubfolder = chk_create_package_subfolder.Checked
            _settings.MaxDownloadThreads = CInt(num_max_threads.Value)
            _settings.MaxRetry = CInt(num_max_retries.Value)
            _settings.RetryWaitTime = CInt(num_retry_wait_time.Value)
            _settings.MarkAllContainerFiles = chk_mark_all_files.Checked

            _settings.InstantVideo = chk_instantvideo.Checked
            _settings.ClicknLoadEnabled = chk_clicknload.Checked
            _settings.SearchUpdates = chk_search_updates.Checked
            _settings.Language = ComB_Language.Text.ToLower
            _settings.DeleteSFDLAfterOpen = chk_delete_sfdl_after_open.Checked

            _unrar_settings.DeleteAfterUnRAR = chk_unrar_del_files.Checked
            _unrar_settings.UnRARAfterDownload = chk_unrar_auto.Checked

            For Each _pwd In ListUnRARPwd.Items
                _unrar_settings.UnRARPasswordList.Add(_pwd.ToString)
            Next

            _unrar_settings.UseUnRARPasswordList = chk_unrar_pwd_list.Checked

            If rd_speedreport_show.Checked Then
                _speedreport_settings.SpeedreportView = SpeedreportView.ShowGUI
            End If

            If rd_speedreport_write2file.Checked Then
                _speedreport_settings.SpeedreportView = SpeedreportView.Write2File
            End If

            If rd_speedreport_hide.Checked Then
                _speedreport_settings.SpeedreportView = SpeedreportView.Hide
            End If

            _speedreport_settings.SpeedreportComment = txt_speed_var_comment.Text
            _speedreport_settings.SpeedreportConnection = txt_speed_var_connection.Text
            _speedreport_settings.SpeedreportTemplate = rtb_speedreport.Text.ToString
            _speedreport_settings.SpeedreportUsername = txt_speed_var_username.Text

            _settings.UnRARSettings = _unrar_settings
            _settings.SpeedReportSettings = _speedreport_settings


            With _settings.RemoteControlSettings

                For Each _key In List_APIKeys.Items
                    .APIKeyList.Add(_key.ToString)
                Next

                .Enabled = chk_rc_enabled.Checked
                .IPAdress = txt_rc_ip_adress.Text
                .Port = CInt(num_rc_port.Value)

            End With

            SavePluginSettings()

            _tools.XMLSerialize(_settings, GetSettingsPath)

            _eventargs.NewSettings = _settings

            RaiseEvent SettingsUpdated(Me, _eventargs)

            _log.Info("Einstellungen gespeichert!")

            MessageBox.Show(StringMessages.SettingsSaveSuccessPrompt, StringMessages.SettingsSaveSuccessTitle, MessageBoxButtons.OK, MessageBoxIcon.Information)

            Me.Close()

        Catch ex As Exception
            _log.Error(ex, ex.Message)
            MessageBox.Show(StringMessages.SettingsSaveGeneralErrorPrompt, StringMessages.SettingsSaveGeneralErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub

    Private Sub frm_settings_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim _settings As New Settings

        Try

            _settings = GetSettings

            _log.Info("Lade Einstellungen...")

            txt_download_dir.Text = _settings.DownloadDirectory

            If _settings.ExistingFileHandling = ExistingFileHandling.ResumeFile Then
                ComB_Existing_File_Handling.SelectedIndex = 0
            End If

            If _settings.ExistingFileHandling = ExistingFileHandling.OverwriteFile Then
                ComB_Existing_File_Handling.SelectedIndex = 1
            End If

            chk_send2tray.Checked = _settings.Send2Tray

            chk_prevent_standby.Checked = _settings.PreventStandby

            chk_create_sub_folder.Checked = _settings.CreateDownloadDir
            rd_sub_folder_description.Checked = _settings.CreateDownloadDirUseDescription
            rd_sub_folder_filename.Checked = _settings.CreateDownloadDirUseFilename
            chk_create_package_subfolder.Checked = _settings.CreatePackageSubfolder

            If _settings.CreateDownloadDirUseDescription = False And _settings.CreateDownloadDirUseFilename = False Then
                rd_sub_folder_filename.Checked = True
            End If

            If _settings.MaxDownloadThreads = 0 Then
                num_max_threads.Value = 1
            Else
                num_max_threads.Value = _settings.MaxDownloadThreads
            End If

            num_max_retries.Value = _settings.MaxRetry
            num_retry_wait_time.Value = _settings.RetryWaitTime

            chk_clicknload.Checked = _settings.ClicknLoadEnabled
            chk_instantvideo.Checked = _settings.InstantVideo

            chk_mark_all_files.Checked = _settings.MarkAllContainerFiles

            chk_search_updates.Checked = _settings.SearchUpdates

            chk_delete_sfdl_after_open.Checked = _settings.DeleteSFDLAfterOpen

            Select Case _settings.Language

                Case "de-de"

                    ComB_Language.SelectedIndex = 0

                Case "en-us"

                    ComB_Language.SelectedIndex = 1

                Case Else

                    ComB_Language.SelectedIndex = 0

            End Select

            Select Case _settings.SpeedReportSettings.SpeedreportView

                Case SpeedreportView.ShowGUI

                    rd_speedreport_show.Checked = True

                Case SpeedreportView.Write2File

                    rd_speedreport_write2file.Checked = True

                Case SpeedreportView.Hide

                    rd_speedreport_hide.Checked = True

            End Select

            txt_speed_var_comment.Text = _settings.SpeedReportSettings.SpeedreportComment
            txt_speed_var_connection.Text = _settings.SpeedReportSettings.SpeedreportConnection
            txt_speed_var_username.Text = _settings.SpeedReportSettings.SpeedreportUsername
            rtb_speedreport.Text = _settings.SpeedReportSettings.SpeedreportTemplate

            chk_unrar_auto.Checked = _settings.UnRARSettings.UnRARAfterDownload
            chk_unrar_del_files.Checked = _settings.UnRARSettings.DeleteAfterUnRAR
            chk_unrar_pwd_list.Checked = _settings.UnRARSettings.UseUnRARPasswordList

            ListUnRARPwd.Items.Clear()
            For Each _pwd In _settings.UnRARSettings.UnRARPasswordList
                ListUnRARPwd.Items.Add(_pwd.ToString)
            Next

            List_APIKeys.Items.Clear()
            txt_rc_ip_adress.Text = _settings.RemoteControlSettings.IPAdress
            num_rc_port.Value = _settings.RemoteControlSettings.Port
            List_APIKeys.Items.AddRange(_settings.RemoteControlSettings.APIKeyList.ToArray)


            _log.Info("Einstellungen geladen!")
            _log.Info("Lade Plugin Einstellungen...")

            For Each _plugin In GetPluginConnectorInstance.ClicknLoadPlugins
                TabControlMain_Settings.TabPages.RemoveByKey(_plugin.GetName)
            Next

            LoadPluginSettings()

            _log.Info("Plugin Einstellungen geladen")

        Catch ex As Exception
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            _log.Error(ex, ex.Message)
        End Try

    End Sub

#End Region

#Region "Download Einstellungen"

    Private Sub cmd_choose_download_dir_Click(sender As Object, e As EventArgs) Handles cmd_choose_download_dir.Click

        If Not FBD_Download_Dir.ShowDialog = DialogResult.Cancel Then
            txt_download_dir.Text = FBD_Download_Dir.SelectedPath
        End If

    End Sub

    Private Sub chk_create_sub_folder_CheckedChanged(sender As Object, e As EventArgs) Handles chk_create_sub_folder.CheckedChanged
        If chk_create_sub_folder.Checked Then
            rd_sub_folder_description.Enabled = True
            rd_sub_folder_filename.Enabled = True
        Else
            rd_sub_folder_description.Enabled = False
            rd_sub_folder_filename.Enabled = False
        End If
    End Sub

#End Region

#Region "Speedreport Tab"

    Private Sub cmd_insert_var_username_Click(sender As Object, e As EventArgs) Handles cmd_insert_var_username.Click
        InsertTextAtCursor("%%USER%%")
    End Sub

    Private Sub cmd_insert_var_connection_Click(sender As Object, e As EventArgs) Handles cmd_insert_var_connection.Click
        InsertTextAtCursor("%%CONNECTION%%")
    End Sub

    Private Sub cmd_insert_var_comment_Click(sender As Object, e As EventArgs) Handles cmd_insert_var_comment.Click
        InsertTextAtCursor("%%COMMENT%%")
    End Sub

    Private Sub DownloadGeschwindigkeitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DownloadGeschwindigkeitToolStripMenuItem.Click
        InsertTextAtCursor("%%SPEED%%")
    End Sub

    Private Sub BeschreibungToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BeschreibungToolStripMenuItem.Click
        InsertTextAtCursor("%%SFDL_DESC%%")
    End Sub

    Private Sub UpperToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles UpperToolStripMenuItem.Click
        InsertTextAtCursor("%%SFDL_UPPER%%")
    End Sub

    Private Sub BenötigteDownloadzeitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BenötigteDownloadzeitToolStripMenuItem.Click
        InsertTextAtCursor("%%TIME%%")
    End Sub

    Private Sub InsertTextAtCursor(ByVal _text As String)

        rtb_speedreport.Text = rtb_speedreport.Text.Insert(rtb_speedreport.SelectionStart, _text)

        rtb_speedreport.SelectionStart = rtb_speedreport.Text.Length

        rtb_speedreport.ScrollToCaret()

    End Sub

    Private Sub GesamtdownloadgrößeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles GesamtdownloadgrößeToolStripMenuItem.Click
        InsertTextAtCursor("%%SFDL_SIZE%%")
    End Sub

#End Region

#Region "UnRAR Tab"

    Private Sub cmd_add_password_Click(sender As Object, e As EventArgs) Handles cmd_add_password.Click

        Dim _input As String = String.Empty

        _input = InputBox(StringMessages.SettingsAddUnRARPasswordPrompt, StringMessages.SettingsAddUnRARPasswordTitle)

        If Not String.IsNullOrWhiteSpace(_input) Then
            ListUnRARPwd.Items.Add(_input)
        End If

    End Sub

    Private Sub cmd_del_password_Click(sender As Object, e As EventArgs) Handles cmd_del_password.Click

        Dim _index_remove_list As New List(Of Integer)

        If MessageBox.Show(StringMessages.SettingsRemoveUnRARPasswordQuestionPrompt, StringMessages.SettingsRemoveUnRARPasswordQuestionTitle, MessageBoxButtons.YesNo) = DialogResult.Yes Then

            _index_remove_list.AddRange(From _item As Object In ListUnRARPwd.SelectedItems Select ListUnRARPwd.FindStringExact(_item.ToString))

            For Each _index_item In _index_remove_list
                ListUnRARPwd.Items.RemoveAt(_index_item)
            Next

        End If

    End Sub

    Private Sub cmd_new_api_key_Click(sender As Object, e As EventArgs) Handles cmd_new_api_key.Click

        Dim _key As String

        _key = RandomString(36)

        List_APIKeys.Items.Add(_key)

    End Sub

    Private Sub cmd_remove_api_key_Click(sender As Object, e As EventArgs) Handles cmd_remove_api_key.Click

        If MessageBox.Show(Me, "API Key wirklich entfernen?", "Key entfernen", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
            List_APIKeys.Items.Remove(List_APIKeys.SelectedItem)
        End If

    End Sub


#End Region

End Class

Public Class SettingsUpatedEventArgs
    Inherits EventArgs
    Public NewSettings As Settings
End Class